package com.xxy.book.vo;

import com.xxy.book.enums.StatusCodeEnum;
import lombok.Data;

import static com.xxy.book.enums.StatusCodeEnum.*;

/**
 * @Author Xu XianYun
 * @Date 2023-01-05
 * @Description
 */

@Data
public class Result<T> {

    //返回状态
    private Boolean flag;

    //返回码
    private Integer code;

    //返回信息
    private String message;

    //返回数据
    private T data;

    //操作成功，没有其他数据返回
    public static <T> Result<T> ok() {
        return restResult(true,null, SUCCESS.getCode(), SUCCESS.getDesc());
    }

    //操作成功，返回数据
    public static <T> Result<T> ok(T data) {
        return restResult(true, data, SUCCESS.getCode(), SUCCESS.getDesc());
    }

    //操作成功，返回数据和消息
    public static <T> Result<T> ok(T data, String message) {
        return restResult(true, data, SUCCESS.getCode(), message);
    }

    //操作失败，没有其他数据返回
    public static <T> Result<T> fail() {
        return restResult(false, null, FAIL.getCode(), FAIL.getDesc());
    }

    //操作失败，返回状态码和提示信息(封装在枚举类型中)
    public static <T> Result<T> fail(StatusCodeEnum statusCodeEnum) {
        return restResult(false, null, statusCodeEnum.getCode(), statusCodeEnum.getDesc());
    }

    //操作失败，返回提示信息
    public static <T> Result<T> fail(String message) {
        return restResult(false, message);
    }

    //操作失败，返回数据
    public static <T> Result<T> fail(T data) {
        return restResult(false, data, FAIL.getCode(), FAIL.getDesc());
    }

    //操作失败，返回数据和自定义提示信息
    public static <T> Result<T> fail(T data, String message) {
        return restResult(false, data, FAIL.getCode(), message);
    }

    //操作失败，返回状态码和提示信息
    public static <T> Result<T> fail(Integer code, String message) {
        return restResult(false, null, code, message);
    }

    private static <T> Result<T> restResult(Boolean flag, String message) {
        Result<T> apiResult = new Result<>();
        apiResult.setCode(flag ? SUCCESS.getCode() : FAIL.getCode());
        apiResult.setFlag(flag);
        apiResult.setMessage(message);
        return apiResult;
    }

    private static <T> Result<T> restResult(Boolean flag, T data, Integer code, String message) {
        Result<T> apiResult = new Result<>();
        apiResult.setFlag(flag);
        apiResult.setData(data);
        apiResult.setCode(code);
        apiResult.setMessage(message);
        return apiResult;
    }
}
